package com.checkchan.ethshare.service.user;

import com.checkchan.ethshare.model.AccountInfo;
import com.checkchan.ethshare.util.Web3jClient;
import org.springframework.stereotype.Service;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.methods.response.EthGetBalance;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

@Service
public class AccountServiceImp implements AccountService {

    private static Web3j web3j = Web3jClient.getClient();

    @Override
    public List<String> getAccountList() {
        try{
            return web3j.ethAccounts().send().getAccounts();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String createAccount(String name, String password, AccountInfo accountInfo) {

        return "功能未开放";
    }

    @Override
    public AccountInfo getAccountInfo(String accountId) {
        return null;
    }

    @Override
    public String checkAccount(String accountAddress) {
        try {
            List<String> accountList = web3j.ethAccounts().send().getAccounts();
            for (String account :
                    accountList) {
                if (accountAddress.equals(account)){
                    return accountAddress;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public BigDecimal getBalance(String accountAddress) {
        try {
            EthGetBalance ethBalance = web3j.ethGetBalance(accountAddress, DefaultBlockParameter.valueOf("latest")).send();
            BigDecimal balance = new BigDecimal(ethBalance.getBalance().divide(new BigInteger("10000000000000")).toString());
            BigDecimal nbalance = balance.divide(new BigDecimal("100000"), 8, BigDecimal.ROUND_DOWN);
            return nbalance;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
